/*
 * @Description:
 * @Author: SongWenJie
 * @LastEditors: SongWenJie
 * @Date: 2024-07-19 16:40:45
 * @LastEditTime: 2024-07-20 01:03:51
 */
import React, { useEffect, useState } from "react";
import { useHistory, useLocation } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { getUserInfo } from "../../api/user";
import { setUserInfo, clearUserInfo } from "../../store/userSlice";

const AuthWrapper = ({ children }) => {
  const [isLoading, setIsLoading] = useState(true);
  const history = useHistory();
  const location = useLocation();
  const dispatch = useDispatch();
  const userInfo = useSelector((state) => { 
    console.log('state',state)
    return state.user
  });

  useEffect(() => {
    const checkUserInfo = async () => {
      const token = localStorage.getItem("token");
      if (!token) {
        if (location.pathname !== "/login") {
          history.push("/login");
        }
        setIsLoading(false);
        return;
      }

      try {
        const response = await getUserInfo();
        if (response.code === 0) {
          dispatch(setUserInfo(response.data));
          if (location.pathname === "/login") {
            history.push("/");
          }
          console.log("User info set successfully");
        } else {
          throw new Error("Invalid user info");
        }
      } catch (error) {
        console.error("Error fetching user info:", error);
        dispatch(clearUserInfo());
        localStorage.removeItem("token");
        if (location.pathname !== "/login") {
          history.push("/login");
        }
      }

      setIsLoading(false);
    };

    checkUserInfo();
  }, [dispatch, history, location.pathname]);

  if (isLoading) {
    return <div>Loading...</div>;
  }
  if (!userInfo.userName && location.pathname !== "/login") {
    history.push("/login");
    return null;
  }

  return <>{children}</>;
};

export default AuthWrapper;

